$(function(){
    var User = Backbone.Model.extend({
        urlRoot: '/user',
    });

    var Topic = Backbone.Model.extend({
        urlRoot: '/topic',
    });

    var Message = Backbone.Model.extend({
        urlRoot: '/message',
    });

    var Topics = Backbone.Collection.extend({
        url: '/topic',
        model: Topic,
    });

    var Messages = Backbone.Collection.extend({
        url: '/message',
        model: Message,
    });

    var topics = new Topics;

    var TopicView = Backbone.View.extend({
        tagName:  "div",

        // 渲染列表页模板
        render: function() {
//      	console.log("topic render");
//      	console.log(this.model);
			var temp = template("topic-template", this.model);
//			console.log(temp);
        	return  temp;
        },
    });

    var MessageView = Backbone.View.extend({
        tagName:  "div",
        
        // 渲染列表页模板
        render: function() {
        	return template("message-template", this.model);
        },
    });

    var UserView = Backbone.View.extend({
        el: "#username",
        username: $('#username'),

        show: function(username) {
            this.username.html(username);
            this.$el.show();
        },
    });

    var AppView = Backbone.View.extend({
        el: "#main-box",
        topic_list: $("#topic-list"),
        topic_section: $("#topic-box"),
        add_topic: $("#add-topic-box"),
        message_section: $("#message-box"),
        message_list: $("#message-list"),
        message_head: $("#message-head"),

        events: {
            'click #add-message-btn': 'saveMessage',
            'click #add-topic-btn': 'saveTopic',
            'keypress #add-message-input': 'saveMessageEvent',
        },

        initialize: function() {
            _.bindAll(this, 'addTopic', 'addMessage');

            topics.bind('add', this.addTopic);

            // 定义消息列表池，每个topic有自己的message collection
            // 这样保证每个主题下得消息不冲突
            this.message_pool = {};
            this.message_list_div = document.getElementById('message-list');
        },

        addTopic: function(topic) {
//      	console.log("addtopic============");
//      	console.log(topic.attributes)
            var view = new TopicView({model: topic.attributes});
            var html = view.render();
//          console.log(html);
            this.topic_list.append(html);
        },

        addMessage: function(message) {
        	console.log(message);
        	console.log("here");
        	if(message.attributes.content != null){
        		var view = new MessageView({model: message.attributes});
            	this.message_list.append(view.render());
        	}
            
        },

        saveMessageEvent: function(evt) {
            if (evt.keyCode == 13) {
                this.saveMessage(evt);
            }
        },
        saveMessage: function(evt) {
            var comment_box = $('#add-message-input');
            var content = comment_box.val();
            if (content == '') {
                alert('内容不能为空');
                return false;
            }
            var topic_id = comment_box.attr('topic_id');
            console.log("save message topic_id ="+topic_id);
            var message = new Message({
                content: content,
                topic_id: topic_id,
            });
            self = this;
            var messages = this.message_pool[topic_id];
            message.save(null, {
                success: function(model, response, options){
                    comment_box.val('');
                    console.log(response);
                    
                    self.message_list.html("");
                    self.showMessage(topic_id);
                    // 重新获取，看服务器端是否有更新
                    // 比较丑陋的更新机制
//                  messages.fetch({
//                      data: {topic_id: topic_id},
//                      success: function(){
//                          self.message_list.scrollTop(self.message_list_div.scrollHeight);
//                          messages.add(response.data);
//                      },
//                  });
                },
            });
        },

        saveTopic: function(evt) {
            var topic_title = $('#add-topic-input');
            if (topic_title.val() == '') {
                alert('主题不能为空！');
                return false
            }
            var topic = new Topic({
                title: topic_title.val(),
            });
            self = this;
            topic.save(null, {
                success: function(model, response, options){
                    topics.add(response.data);
                    topic_title.val('');
                },
            });
        },

        showTopic: function(){
            topics.fetch();
            this.topic_section.show();
            this.add_topic.show();
            this.message_section.hide();
            this.message_list.html('');
        },

        initMessage: function(topic_id) {
            var messages = new Messages;
            messages.bind('add', this.addMessage);
            this.message_pool[topic_id] = messages;
        },

        showMessage: function(topic_id) {
            this.initMessage(topic_id);
            this.add_topic.hide();
			
            this.message_section.show();
            this.topic_section.hide();

            this.showMessageHead(topic_id);
            $('#add-message-input').attr('topic_id', topic_id);
            console.log("showmessage  topic_id:"+topic_id);
            var messages = this.message_pool[topic_id];
            messages.fetch({
                data: {topic_id: topic_id},
                success: function(resp) {
                    self.message_list.scrollTop(self.message_list_div.scrollHeight)
                }
            });
        },

        showMessageHead: function(topic_id) {
            var topic = new Topic({id: topic_id});
            self = this;
            topic.fetch({
                success: function(res, model, options){
                	console.log("message head" + res);
//              	console.log(res);
                    self.message_head.html(res.attributes.data.title);
                }
            });
        },
    });


    var LoginView = Backbone.View.extend({
        el: "#login-reg-box",
        wrapper: $('#login-reg-box'),
        
        events: {
            'keypress #login-pwd': 'loginEvent',
            'click #login-btn': 'login',
            'keypress #reg-pwd-repeat': 'registeEvent',
            'click #reg-btn': 'registe',
        },

        hide: function() {
            this.wrapper.hide();
        },

        show: function() {
            this.wrapper.show();
        },

        loginEvent: function(evt) {
            if (evt.keyCode == 13) {
                this.login(evt);
            }
        },

        login: function(evt){
            var username_input = $('#login-username');
            var pwd_input = $('#login-pwd');
            var u = new User({
                username: username_input.val(),
                password: pwd_input.val(),
            });
            u.save(null, {
                url: '/login',
                success: function(model, res, options){
                	console.log("登陆成功");
                	console.log(res.data);
                    g_user = res.data;
                    // 跳转到index
                    appRouter.navigate('index', {trigger: true});
                }
            });
        },

        registeEvent: function(evt) {
            if (evt.keyCode == 13) {
                this.registe(evt);
            }
        },

        registe: function(evt){
            var reg_username_input = $('#reg-username');
            var reg_pwd_input = $('#reg-pwd');
            var reg_pwd_repeat_input = $('#reg-pwd-repeat');
            var u = new User({
                username: reg_username_input.val(),
                password: reg_pwd_input.val(),
                password_repeat: reg_pwd_repeat_input.val(),
            });
            u.save(null, {
                success: function(model, res, options){
                    g_user = res.data;
                    // 跳转到index
                    appRouter.navigate('index', {trigger: true});
                }
            });
        },
    });

    var AppRouter = Backbone.Router.extend({
        routes: {
            "login": "login",
            "index": "index",
            "topic/:id" : "topic",
        },

        initialize: function(){
            // 初始化项目, 显示首页
            this.appView = new AppView();
            this.loginView = new LoginView();
            this.userView = new UserView();
            this.indexFlag = false;
        },

        login: function(){
            this.loginView.show();
        },

        index: function(){
            if (g_user && g_user.id != undefined) {
                this.appView.showTopic();
                this.userView.show(g_user.username);
                this.loginView.hide();
                this.indexFlag = true;  // 标志已经到达主页了
            }
        },

        topic: function(topic_id) {
            if (g_user && g_user.id != undefined) {
            	console.log("topic路由 topic_id"+ topic_id);
                this.appView.showMessage(topic_id);
                this.userView.show(g_user.username);
                this.loginView.hide();
                this.indexFlag = true;  // 标志已经到达主页了
            }
        },
    });

    var appRouter = new AppRouter();
    var g_user = new User;
    console.log("start");
    g_user.fetch({
        success: function(model, res, options){
        	console.log("g_user:"+res);
            g_user = res.data;
            Backbone.history.start({pustState: true});

            if(g_user === null || g_user.id === undefined) {
            	console.log("guser null");
                // 跳转到登录页面
                appRouter.navigate('login', {trigger: true});
            } else if (appRouter.indexFlag == false){
            	console.log("guser not null");
            	
                // 跳转到首页
                appRouter.navigate('index', {trigger: true});
            }
        },
    }); // 获取当前用户
});
